//
//  NewFeatureViewController.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/9/5.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

private let GXNewFeatureCellID = "Cell"
private let GXNewFeatureCount = 4

class NewFeatureViewController: UICollectionViewController {

    // 实现一个init的构造函数，指定布局，外部使用，不需要指点指定布局属性
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareLayout()
        
        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier:GXNewFeatureCellID)

    }
    
     // MARK: - 设置布局
    private func prepareLayout() {
        // 获取 collection的布局方式
        let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        // 设置布局的属性
        layout.itemSize = UIScreen.mainScreen().bounds.size;
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
    
     // MARK: - collectionView的代理方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return GXNewFeatureCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GXNewFeatureCellID, forIndexPath: indexPath) as! NewFeatureCell
        print("cell \(indexPath.item)")
        cell.imageIndex = indexPath.item
        return cell
    }
}


class NewFeatureCell: UICollectionViewCell {
    
    /// 为了获得Cell的 indexPath.item
    /// 需要使用 set 的方式实现，因为 执行循序是 先执行init 然后在 cell.imageIndex = indexPath.item
    var imageIndex : Int = 0 {
        didSet {
            let imageName = "new_feature_\(imageIndex + 1)"
            iconView.image = UIImage(named: imageName)
            
            
            if imageIndex == (GXNewFeatureCount - 1) {
                showStartButton()
            }

        }
    }
    
    private func showStartButton() {
        
        startButton.hidden = false
        
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        // Damping 弹性系数，0~1，越小越弹
        // Velocity: 初始速度
        UIView.animateWithDuration(1.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: [], animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                
        }
        
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: [], animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
        }
        
        
    }
    
    @objc func startButtonClicked() {
        // 利用通知发消息
        NSNotificationCenter.defaultCenter().postNotificationName(GXSwitchRootViewControllerNotification, object: nil, userInfo: nil)
    }
    
    /// frame 的大小来自于 layout 的 itemSize
    /// 纯代码实现调用
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        startButton.hidden = true
    }
    
    // xib 或者 sb 的方法实现
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        startButton.hidden = true
    }

    /// 添加子控件
    private func setupUI() {
        
        // 1.添加控件
        addSubview(iconView)
        addSubview(startButton)
        
        // 2.设置布局
        iconView.frame = bounds
        
        startButton.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))

    }
    
     // MARK: - 懒加载的方式加载控件
    private lazy var iconView = UIImageView()
    private lazy var startButton:UIButton = {
        
        let button = UIButton()
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "startButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.sizeToFit()
        
        return button
    }()
}

